package org.toycode.logindemo.application.tapestry.pages;

import javax.ejb.EJBException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.Errors;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.corelib.components.Label;
import org.apache.tapestry5.corelib.components.PasswordField;
import org.apache.tapestry5.corelib.components.TextField;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.toycode.logindemo.application.util.EjbUtil;
import org.toycode.logindemo.entity.SystemUser;
import org.toycode.logindemo.service.SecurityServiceRemote;

/**
 * This class provides registration for users.
 *
 * @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
 * @version 1.0.0.1, Aug 19, 2009
 */
public class Register {

    /**
     * errors for form validation. 
     */
    @Component
    private Errors errors;
    /**
     * message for name filed validation.
     */
    @Component(parameters = {"for=userName"})
    private Label nameLabel;
    /**
     * user name input text field.
     */
    @Component(parameters = {"label=message:user-name", "value=name", "validate=required"})
    private TextField userName;
    /**
     * message for password filed validation.
     */
    @Component(parameters = {"for=userPassword"})
    private Label passwordLabel;
    /**
     * user password input text field.
     */
    @Component(parameters = {"label=message:user-password", "value=password", "validate=required"})
    private PasswordField userPassword;
    /**
     * message for confirm password filed validation.
     */
    @Component(parameters = {"for=confirmPassword"})
    private Label confirmPwdLabel;
    /**
     * user password confirmation field.
     */
    @Component(parameters = {"label=message:password-confirm", "value=confirmPwd", "validate=required"})
    private PasswordField confirmPassword;
    /**
     * register form.
     */
    @Component
    private Form registerForm;
    /**
     * login page.
     */
    @InjectPage
    private Login login;
    /**
     * user name.
     */
    @Property
    private String name;
    /**
     * user password.
     */
    @Property
    private String password;
    /**
     * user password confirmation.
     */
    @Property
    private String confirmPwd;
    /**
     * logger.
     */
    private Logger logger = LoggerFactory.getLogger(Register.class);
    /**
     * security service.
     */
    private SecurityServiceRemote securityService;
    /**
     * messages.
     */
    @Inject
    private Messages messages;

    /**
     * Register form event handler method.
     *
     * @return if register succeed, returns <code>login</code>, otherwise,
     * returns <code>null</code>
     */
    public Object onSuccessFromRegisterForm() {
        securityService = EjbUtil.getEjb(SecurityServiceRemote.class);
        if (securityService == null) {
            registerForm.recordError(messages.get("remote-connect-exception"));
            return null;
        }
        
        final SystemUser userExists = securityService.getUserByName(name);
        if (userExists != null) {
            registerForm.recordError(userName, messages.get("user-exists"));
            return null;
        }

        if (!password.equals(confirmPwd)) {
            password = null;
            registerForm.recordError(userPassword, messages.get("passwords-dont-match"));
            return null;
        }

        final SystemUser user = new SystemUser();

        user.setName(name);
        final String passwordEncoded = DigestUtils.md5Hex(password);
        user.setPassword(passwordEncoded);

        logger.debug("Registering a new user[name=" + name + "]....");


        try {
            securityService.addUser(user);
            return login;
        } catch (final EJBException ex) {
            logger.error("Can't register this user!", ex);

        }

        return null;
    }
}
